import Message from 'tdesign-miniprogram/message/index';
import { cloudHanAPI } from '~/api/post';
const authUtils = require('~/utils/auth.js');

Page({
  data: {
    // 书摘数据
    postData: null,
    postId: '',
    
    // 评论相关
    comments: [],
    commentContent: '',
    
    // 回复相关
    replyTarget: '', // 回复目标用户昵称
    replyCommentId: '', // 回复的评论ID
    
    // 加载状态
    loading: false,
    commentsLoading: false,
    
    // 分页
    commentsPagination: {
      page: 1,
      pageSize: 20,
      hasMore: true
    }
  },

  onLoad(options) {
    console.log('评论详情页加载，参数:', options);
    
    const { id, tab } = options;
    if (!id) {
      wx.showToast({
        title: '参数错误',
        icon: 'error'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      return;
    }

    this.setData({ postId: id });
    
    // 检查登录状态
    if (!authUtils.isLoggedIn()) {
      authUtils.redirectToLogin(`/pages/post-detail/index?id=${id}&tab=${tab || ''}`);
      return;
    }

    // 从全局状态获取卡片数据
    const app = getApp();
    if (app.globalData && app.globalData.currentPostDetail) {
      console.log('使用传递的卡片数据:', app.globalData.currentPostDetail);
      this.setData({ 
        postData: app.globalData.currentPostDetail 
      });
      // 清除全局数据
      app.globalData.currentPostDetail = null;
    } else {
      console.log('未找到传递的数据，可能需要重新获取');
      // 如果没有传递数据，可以考虑返回或显示错误
      wx.showToast({
        title: '数据加载失败',
        icon: 'error'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      return;
    }

    // 只需要加载评论列表
    this.loadComments();
  },


  /**
   * 加载评论列表
   */
  async loadComments(refresh = false) {
    if (this.data.commentsLoading) return;

    try {
      this.setData({ commentsLoading: true });
      
      const { commentsPagination } = this.data;
      if (refresh) {
        commentsPagination.page = 1;
        commentsPagination.hasMore = true;
      }

      if (!commentsPagination.hasMore && !refresh) return;

      const response = await cloudHanAPI.getPostComments(this.data.postId, {
        page: commentsPagination.page,
        pageSize: commentsPagination.pageSize
      });

      console.log('评论列表响应:', response);

      if (response.code === 200) {
        const { list, hasMore } = response.data;
        const formattedComments = this.formatComments(list);
        
        this.setData({
          comments: refresh ? formattedComments : [...this.data.comments, ...formattedComments],
          commentsPagination: {
            ...commentsPagination,
            page: commentsPagination.page + 1,
            hasMore: hasMore
          }
        });
      } else {
        throw new Error(response.message || '加载评论失败');
      }
    } catch (error) {
      console.error('加载评论失败:', error);
      Message.error({
        context: this,
        content: '加载评论失败',
        duration: 2000
      });
    } finally {
      this.setData({ commentsLoading: false });
    }
  },


  /**
   * 格式化评论数据
   */
  formatComments(comments) {
    return comments.map((comment, index) => ({
      ...comment,
      // 楼层号（从1开始）
      floor: (this.data.commentsPagination.page - 1) * this.data.commentsPagination.pageSize + index + 1,
      // 格式化时间
      createdAt: this.formatTime(comment.createdAt),
      // 确保用户信息
      user: {
        nickname: comment.user?.nickname || comment.userName || '匿名用户',
        avatar: this.processImageUrl(comment.user?.avatar || comment.userAvatar || '/static/default-avatar.png', require('~/config/index.js').default),
        id: comment.user?.id || comment.userId
      },
      // 格式化回复列表
      replies: (comment.replies || []).map(reply => ({
        ...reply,
        createdAt: this.formatTime(reply.createdAt),
        user: {
          nickname: reply.user?.nickname || reply.userName || '匿名用户',
          avatar: this.processImageUrl(reply.user?.avatar || reply.userAvatar || '/static/default-avatar.png', require('~/config/index.js').default),
          id: reply.user?.id || reply.userId
        }
      }))
    }));
  },

  /**
   * 处理图片URL
   */
  processImageUrl(imageUrl, config) {
    if (!imageUrl) return '/static/home/card0.png';
    
    if (imageUrl.startsWith('http') || imageUrl.startsWith('/static/')) {
      return imageUrl;
    }
    
    return `${config.baseUrl}${imageUrl}`;
  },

  /**
   * 格式化时间
   */
  formatTime(timestamp) {
    if (!timestamp) return '';
    
    const date = new Date(timestamp);
    const now = new Date();
    const diff = now - date;
    
    const minute = 60 * 1000;
    const hour = 60 * minute;
    const day = 24 * hour;
    
    if (diff < minute) {
      return '刚刚';
    } else if (diff < hour) {
      return Math.floor(diff / minute) + '分钟前';
    } else if (diff < day) {
      return Math.floor(diff / hour) + '小时前';
    } else if (diff < 7 * day) {
      return Math.floor(diff / day) + '天前';
    } else {
      return date.toLocaleDateString();
    }
  },

  /**
   * 返回上一页
   */
  onBack() {
    wx.navigateBack();
  },

  /**
   * 点赞
   */
  async onLike(e) {
    const { postid: postId } = e.currentTarget.dataset;
    
    if (!authUtils.isLoggedIn()) {
      authUtils.redirectToLogin();
      return;
    }

    try {
      const { postData } = this.data;
      const isLiked = postData.isLiked;

      // 前端立即反馈
      this.setData({
        'postData.isLiked': !isLiked,
        'postData.likeCount': isLiked ? Math.max(0, postData.likeCount - 1) : (postData.likeCount || 0) + 1
      });

      // 异步更新数据库
      if (isLiked) {
        await cloudHanAPI.unlikeQuote(postId);
      } else {
        await cloudHanAPI.likeQuote(postId);
      }
    } catch (error) {
      console.error('点赞失败:', error);
      // 回滚UI状态
      const { postData } = this.data;
      this.setData({
        'postData.isLiked': !postData.isLiked,
        'postData.likeCount': postData.isLiked ? (postData.likeCount || 0) + 1 : Math.max(0, postData.likeCount - 1)
      });
      
      Message.error({
        context: this,
        content: '操作失败，请重试',
        duration: 2000
      });
    }
  },

  /**
   * 收藏
   */
  async onFavorite(e) {
    const { postid: postId } = e.currentTarget.dataset;
    
    if (!authUtils.isLoggedIn()) {
      authUtils.redirectToLogin();
      return;
    }

    try {
      const { postData } = this.data;
      const isFavorited = postData.isFavorited;

      // 前端立即反馈
      this.setData({
        'postData.isFavorited': !isFavorited,
        'postData.favoriteCount': isFavorited ? Math.max(0, postData.favoriteCount - 1) : (postData.favoriteCount || 0) + 1
      });

      // 异步更新数据库
      if (isFavorited) {
        await cloudHanAPI.uncollectQuote(postId);
      } else {
        await cloudHanAPI.collectQuote(postId);
      }
    } catch (error) {
      console.error('收藏失败:', error);
      // 回滚UI状态
      const { postData } = this.data;
      this.setData({
        'postData.isFavorited': !postData.isFavorited,
        'postData.favoriteCount': postData.isFavorited ? (postData.favoriteCount || 0) + 1 : Math.max(0, postData.favoriteCount - 1)
      });
      
      Message.error({
        context: this,
        content: '操作失败，请重试',
        duration: 2000
      });
    }
  },

  /**
   * 评论输入
   */
  onCommentInput(e) {
    this.setData({
      commentContent: e.detail.value
    });
  },

  /**
   * 输入框获得焦点
   */
  onInputFocus() {
    console.log('输入框获得焦点');
  },

  /**
   * 输入框失去焦点
   */
  onInputBlur() {
    console.log('输入框失去焦点');
  },

  /**
   * 回复评论
   */
  onReplyComment(e) {
    const { commentid: commentId, nickname } = e.currentTarget.dataset;
    console.log('回复评论:', commentId, nickname);
    
    this.setData({
      replyTarget: nickname,
      replyCommentId: commentId
    });

    // 聚焦输入框
    setTimeout(() => {
      const query = wx.createSelectorQuery();
      query.select('.comment-input').boundingClientRect();
      query.exec();
    }, 100);
  },

  /**
   * 取消回复
   */
  onCancelReply() {
    this.setData({
      replyTarget: '',
      replyCommentId: ''
    });
  },

  /**
   * 发送评论
   */
  async onSendComment() {
    const { commentContent, postId, replyCommentId, replyTarget } = this.data;
    
    if (!commentContent.trim()) {
      Message.warning({
        context: this,
        content: '请输入评论内容',
        duration: 2000
      });
      return;
    }

    if (!authUtils.isLoggedIn()) {
      authUtils.redirectToLogin();
      return;
    }

    try {
      const commentData = {
        content: commentContent.trim(),
        parentId: replyCommentId || null
      };

      console.log('发送评论:', commentData);

      if (replyCommentId) {
        // 回复评论
        await cloudHanAPI.replyComment(replyCommentId, commentData);
        Message.success({
          context: this,
          content: `回复 @${replyTarget} 成功`,
          duration: 2000
        });
      } else {
        // 直接评论
        await cloudHanAPI.commentQuote(postId, commentData);
        Message.success({
          context: this,
          content: '评论成功',
          duration: 2000
        });
      }

      // 清空输入框和回复状态
      this.setData({
        commentContent: '',
        replyTarget: '',
        replyCommentId: ''
      });

      // 重新加载评论列表
      setTimeout(() => {
        this.loadComments(true);
      }, 500);

    } catch (error) {
      console.error('发送评论失败:', error);
      Message.error({
        context: this,
        content: '发送失败，请重试',
        duration: 2000
      });
    }
  },

  /**
   * 页面滚动到底部加载更多评论
   */
  onReachBottom() {
    if (this.data.commentsPagination.hasMore && !this.data.commentsLoading) {
      this.loadComments();
    }
  },

  /**
   * 下拉刷新
   */
  async onPullDownRefresh() {
    try {
      // 只刷新评论列表，书摘数据已经从上一页传递
      await this.loadComments(true);
    } finally {
      wx.stopPullDownRefresh();
    }
  }
});
